package com.flash.dataU.test.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import javax.sound.sampled.Line;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * .
 *
 * @author sunym1993
 * @version 0.0.1-SNAPSHOT
 * @since 2017年11月13日 17时28分
 */
@RestController
public class Socketman {

    @RequestMapping("send")
    public String send(String url, int port, String data){

        StringBuilder info = new StringBuilder();
        try {
            //客户端
            //1、创建客户端Socket，指定服务器地址和端口
            Socket socket =new Socket(url, port);
            //2、获取输出流，向服务器端发送信息
            OutputStream os = socket.getOutputStream();//字节输出流
            PrintWriter pw =new PrintWriter(os);//将输出流包装成打印流
            pw.print(data);
            pw.flush();
            socket.shutdownOutput();
            //3、获取输入流，并读取服务器端的响应信息
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String temp = null;
            while((temp=br.readLine())!=null){
                info.append(temp + "\r\n");
            }

            //4、关闭资源
            br.close();
            is.close();
            pw.close();
            os.close();
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

        return info.toString();
    }

    public static void main(String[] args) {
        try {
            //客户端
            //1、创建客户端Socket，指定服务器地址和端口
            Socket socket =new Socket("www.baidu.com",80);
            //2、获取输出流，向服务器端发送信息
            OutputStream os = socket.getOutputStream();//字节输出流
            PrintWriter pw =new PrintWriter(os);//将输出流包装成打印流
            String data = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\n\r\n";
            pw.print(data);
            pw.flush();
            socket.shutdownOutput();
            //3、获取输入流，并读取服务器端的响应信息
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String info;
            while((info=br.readLine())!=null){
                System.out.println(info);
            }

            //4、关闭资源
            br.close();
            is.close();
            pw.close();
            os.close();
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }



}
